package com.xyzwps.mvckotlin.service

import com.xyzwps.mvckotlin.dao.model.UserInfo
import com.xyzwps.mvckotlin.dao.repository.UserInfoRepository
import org.apache.commons.codec.digest.DigestUtils.sha1Hex
import org.springframework.stereotype.Service
import org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric

@Service
class UserService(val userInfoRepository: UserInfoRepository) {

    companion object {
        private const val SALT_LENGTH = 19
    }

    suspend fun create(username: String, rawPassword: String): UserInfo {
        val newUserInfo = UserInfo(username = username, password = encodePassword(rawPassword))
        return userInfoRepository.create(newUserInfo).await()
    }

    suspend fun checkUsernameExists(username: String): Boolean {
        if (username == "") return false

        val userInfo = userInfoRepository.getByUsername(username).await()
        return userInfo != null
    }

    suspend fun getUserByUsername(username: String): UserInfo? = userInfoRepository.getByUsername(username).await()


    fun checkPassword(rawPassword: String, encodedPassword: String): Boolean {
        val salt = encodedPassword.substring(encodedPassword.length - SALT_LENGTH)
        return encodedPassword == encodePassword(rawPassword, salt)
    }

    private fun encodePassword(password: String): String {
        return encodePassword(password, randomAlphanumeric(SALT_LENGTH))
    }

    private fun encodePassword(password: String, salt: String): String {
        return sha1Hex(sha1Hex(password) + salt) + salt
    }
}